/*
 * Copyright (C) 2010 Yury Kudryashov.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package name.kudryashov.strings;

import java.io.IOException;
import java.util.Arrays;
import java.util.Iterator;

import static name.kudryashov.base.Argument.requireNotNull;

public class Joiner {

    public static Joiner on(String separator) {
        return new Joiner(separator);
    }

    private final String separator;

    private Joiner(String separator) {
        this.separator = String.valueOf(separator);
    }

    public void append(Appendable a, Iterable<?> what) throws IOException {
        requireNotNull(a);
        Iterator<?> iterator = what.iterator();
        append(a, iterator);
    }

    private void append(Appendable a, Iterator<?> iterator) throws IOException {
        if(iterator.hasNext()) {
            a.append(iterator.next().toString());
            while(iterator.hasNext()) {
                a.append(separator);
                a.append(iterator.next().toString());
            }
        }
    }

    public StringBuilder append(StringBuilder sb, Iterable<?> what) {
        try {
            append((Appendable) sb, what);
        } catch (IOException e) {
            throw new AssertionError(); // impossible
        }
        return sb;
    }

    public StringBuilder append(StringBuilder sb, Iterator<?> what) {
        try {
            append((Appendable) sb, what);
        } catch (IOException e) {
            throw new AssertionError(); // impossible
        }
        return sb;
    }

    public String join(Iterable<?> what) {
        return append(new StringBuilder(), what).toString();
    }

    public String join(Iterator<?> what) {
        return append(new StringBuilder(), what).toString();
    }

    public String join(String start, String end, Iterable<?> what) {
        StringBuilder builder = new StringBuilder();
        builder.append(start);
        append(builder, what);
        builder.append(end);
        return builder.toString();
    }

     public String join(String start, String end, Iterator<?> what) {
        StringBuilder builder = new StringBuilder();
        builder.append(start);
        append(builder, what);
        builder.append(end);
        return builder.toString();
    }

    public String join(Object... what) {
        return append(new StringBuilder(), Arrays.asList(what)).toString();
    }
}